package com.yonyou.pmclouds.projectpart.processor;

import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.consts.EnableStatusConst;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.projectpart.entity.ProjectPartVO;
import com.yonyou.pmclouds.projectpart.mapper.ProjectpartMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 工程部位编码检查
 * 1.检查是否修改了父编码
 * 2.检查编码在项目下是否重复
 */
@Component
public class ProjectpartCodeCheckProcessor implements SingleProcessor<ProjectPartVO>{

    @Autowired
    private ProjectpartMapper projectpartMapper;

    @Override
    public void process(ProjectPartVO vo, ProjectPartVO orig) throws BusinessException {
        if("topVirtual".equals(vo.getPkParent()) ){
            vo.setPkParent("~");
        }
        if(!"~".equals(vo.getPkParent())){
            if(StringUtils.isNotEmpty(vo.getPkParent())){
                ProjectPartVO parent =  projectpartMapper.getById(vo.getPkParent());
                if(parent == null){
                    throw new BusinessException("父节点不存在，请检查数据");
                }
                if(!vo.getScode().startsWith(parent.getScode())){
                    throw new BusinessException("不允许修改父编码");
                }
            }
        }

        ProjectPartVO qryVO = new ProjectPartVO();
        qryVO.setPkProject(vo.getPkProject());
        qryVO.setScode(vo.getScode().trim());
        qryVO.setEnableStatus(EnableStatusConst.DISABLE);
        List<ProjectPartVO> result = projectpartMapper.queryVOsByCondition(qryVO);
        if(result.size() > 0){
            if(result.size() > 1){
                throw new BusinessException("编码已存在！");
            }else{
                if(StringUtils.isEmpty(vo.getPkProjectpart())
                        || (!vo.getPkProjectpart().equals(result.get(0).getPkProjectpart()))){
                    throw new BusinessException("编码已存在！");
                }
            }
        }

    }
}
